package com.gemantic.task.config.db;

import java.util.List;
import java.util.Properties;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import cn.hutool.core.collection.ListUtil;
import lombok.extern.slf4j.Slf4j;


//method = "query"拦截select方法、而method = "update"则能拦截insert、update、delete的方法
@Intercepts({
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
@Slf4j
@Component
public class ReplaceTableInterceptor implements Interceptor {

    @Value("${task.replace.flag:false}")
    private boolean taskReplaceFlag;

    @Value("${task.replace.table:task}")
    private String taskReplaceTable;

    private static final String originTaskName = "task";

    List<String> methods = ListUtil.of(
            "com.gemantic.task.dao.local.TaskDao.closeTask",
            "com.gemantic.task.dao.local.TaskDao.pendTask",
            "com.gemantic.task.dao.local.TaskDao.getTasks",
            "com.gemantic.task.dao.local.TaskDao.selectByPrimaryKey",
            "com.gemantic.task.dao.local.TaskDao.lockByPrimaryKey",
            "com.gemantic.task.dao.local.TaskDao.updateByPrimaryKey",
            "com.gemantic.task.dao.local.TaskDao.insertSelective",
            "com.gemantic.task.dao.local.TaskDao.getOpenTaskByOrder",
            "com.gemantic.task.dao.local.TaskDao.getActiveTasks",
            "com.gemantic.task.dao.local.TaskDao.getOpenTask",
            "com.gemantic.task.dao.local.TaskDao.batchUpdate",
            "com.gemantic.task.dao.local.TaskDao.modifyTaskFromUI",
            "com.gemantic.task.dao.local.TaskDao.getAllTaskByOrder"
    );

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        //获取MappedStatement对象
        MappedStatement ms = (MappedStatement) args[0];
        String id = ms.getId();

        if (!methods.contains(id)) {
            return invocation.proceed();
        }

        if ( !taskReplaceFlag || originTaskName.equals(taskReplaceTable) ) {
            return invocation.proceed();
        }


        //获取传入sql语句的参数对象
        Object parameterObject = args[1];

        BoundSql boundSql = ms.getBoundSql(parameterObject);

        if (boundSql.getSql().contains(taskReplaceTable)) {
            return invocation.proceed();
        }

        //获取到拥有占位符的sql语句
        String sql = boundSql.getSql();
        log.debug("拦截前sql :{}" , sql);

        sql = sql.replace(originTaskName,taskReplaceTable);
        log.debug("intercept 拦截后sql :{}" , sql);

        //重新生成一个BoundSql对象
        BoundSql bs = new BoundSql(ms.getConfiguration(), sql, boundSql.getParameterMappings(), parameterObject);

        //重新生成一个MappedStatement对象
        MappedStatement newMs = copyMappedStatement(ms, new BoundSqlSqlSource(bs));

        //赋回给实际执行方法所需的参数中
        args[0] = newMs;

        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        if (target instanceof Executor || target instanceof StatementHandler) {
            return Plugin.wrap(target, this);
        }
        return target;
    }

    @Override
    public void setProperties(Properties properties) {

    }


    /***
     * 复制一个新的MappedStatement
     * @param ms
     * @param newSqlSource
     * @return
     */
    private MappedStatement copyMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
        MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType());

        builder.resource(ms.getResource());
        builder.fetchSize(ms.getFetchSize());
        builder.statementType(ms.getStatementType());
        builder.keyGenerator(ms.getKeyGenerator());
        if (ms.getKeyProperties() != null && ms.getKeyProperties().length > 0) {
            builder.keyProperty(String.join(",", ms.getKeyProperties()));
        }
        builder.timeout(ms.getTimeout());
        builder.parameterMap(ms.getParameterMap());
        builder.resultMaps(ms.getResultMaps());
        builder.resultSetType(ms.getResultSetType());
        builder.cache(ms.getCache());
        builder.flushCacheRequired(ms.isFlushCacheRequired());
        builder.useCache(ms.isUseCache());
        return builder.build();
    }

    /***
     * MappedStatement构造器接受的是SqlSource
     * 实现SqlSource接口，将BoundSql封装进去
     */
    public static class BoundSqlSqlSource implements SqlSource {
        private BoundSql boundSql;

        public BoundSqlSqlSource(BoundSql boundSql) {
            this.boundSql = boundSql;
        }

        @Override
        public BoundSql getBoundSql(Object parameterObject) {
            return boundSql;
        }
    }


}

